package com.myapp.web.struts2.multipart;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.fileupload.ProgressListener;

public class FileUploadListener implements ProgressListener {	
	
	protected Map<Integer,FileItemProgressInfo> filesProgressMap = new HashMap<Integer,FileItemProgressInfo>();
	
	private ProgressChangeListener listener  = null;
	
	private String id;
	
	public FileUploadListener(String id){
		this.id = id;
	}
	
	public void addEventListener(ProgressChangeListener listener){
		this.listener =  listener;
	}
	
	public void removeEventListener(ProgressChangeListener listener){
		if(this.listener == listener){
			this.listener = null;
		}
	}
	private FileItemProgressInfo getItemProgress(int index){
		FileItemProgressInfo info = null;
		if(filesProgressMap.size() > 0 && filesProgressMap.containsKey(index)){
			info = filesProgressMap.get(index);
		}else{
			info = new FileItemProgressInfo();
			filesProgressMap.put(index, info);			
		}
		return info;
	}
	public void SetFileInfo(int index,String fileName,long totalSize){
		if(index < 0 || fileName == null || totalSize < 0)
		{
			return ;
		}
		FileItemProgressInfo info = getItemProgress(index);		
		info.setFileIndex(index);
		info.setFileName(fileName);
		info.setTotalSize(totalSize);
	}
	
	/*public boolean isCompleted(){
		//return finishCount != 0 && finishCount == filesInfo.size() ? true : false;
	}*/
	
	@Override
	public void update(long pBytesRead, long pContentLength, int pItems) {
		if(pItems == 0){
			return ;
		}
		FileItemProgressInfo info = getItemProgress(pItems);	
		info.setTotalSize(pContentLength);
		info.setBytesRead(pBytesRead);
	
		ProgressChangeEvent event = null;
		if(info.isCompleted()){
			event = new ProgressChangeEvent(info,ProgressChangeEvent.EType.COMPLETED);
		}else if(info.isPeriod()){
			event = new ProgressChangeEvent(info,ProgressChangeEvent.EType.PROGRESS);
		}
		if(listener != null && event != null){
			listener.progressChange(event);
		}
		//firedEventIfProgressChanged(info);
	}
		
	public String getId() {
		return id;
	}
}
